package com.lsh.payment.data.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.lsh.payment.core.model.payenum.OperateStatus;
import com.lsh.payment.core.model.payenum.PayStatus;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.service.payment.impl.PayDealService;
import com.lsh.payment.data.model.PayMain;
import com.lsh.payment.data.model.PaymentDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Project Name: lsh-payment
 * Created by peter on 16/11/14.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
public class PaymentSyncService {

    private static Logger logger = LoggerFactory.getLogger(PaymentSyncService.class);

    @Value("${bill.pagesize}")
    private int billSize;

    private static int 预支付 = 1;
    private static int 待支付 = 2;
    private static int 支付中 = 3;
    private static int 已支付 = 4;
    private static int 支付失败 = 5;
    private static int 作废 = 6;
    private static int 失效 = 7;


    private static String BEFORE_FLAG = "b";
    private static String AFTER_FLAG = "a";


    private static String notifyUrl = "http://sjapi.yougong.elianshang.com/pay/paycallback/notify";

    @Resource(name = "payTempJdbcTemplate")
    private NamedParameterJdbcTemplate payTempJdbcTemplate;

    @Autowired
    private PayDealService payDealService;

    /**
     * 同步支付数据
     */
    public void selectPayMainForSync(String flag, int time) {

        //数据库总数量
        int sum = selectSum(flag, time);

        logger.info("数据总量是 : " + sum);

        int pageSize = billSize;

        int start = 0;

        int limit = pageSize;

        int page = 1;

        while (((page - 1) * pageSize) < sum) {

            logger.info("start is : " + start + " , limit is " + limit);

            logger.info(" 第 (" + page + ") 批数据同步");

            logger.info("  PayMain 查询开始");
            List<PayMain> paymainList = selectPayMainListByPage(start, pageSize, flag, time);
            logger.info("  PayMain 查询结束");
            logger.info(" paymainList size is : " + paymainList.size());

            logger.info("  组织paydeal开始");
            List<PayDeal> payDealList = groupPayDealfromPayMain(paymainList);
            logger.info(" payDealList size is : " + payDealList.size());
            logger.info("  组织paydeal结束");

            logger.info("  插入开始");
            insertBatch(payDealList);
            logger.info("  插入结束");

            start = page * pageSize;

            page += 1;

            limit = page * pageSize;

        }

    }

    /**
     * 查询支付订单流水数据数量
     *
     * @return
     */
    public int selectSum(String flag, int time) {

        String sql = "select count(id) from pay_main ";
        Map<String, Object> map = new HashMap<String, Object>(1);

        if (!StringUtils.isBlank(flag)) {
            if (BEFORE_FLAG.equals(flag)) {
                sql += "where created_at <= :time";
            } else {
                sql += "where created_at > :time";
            }
            map.put("time", time);
        }
        return this.payTempJdbcTemplate.queryForObject(sql, map, Integer.class);
    }

    /**
     * 批量数据插入
     *
     * @param payDealList
     */
    public void insertBatch(List<PayDeal> payDealList) {

        payDealService.insertBatch(payDealList);
    }

    /**
     * 分页查询支付记录数据(旧数据)
     *
     * @param start
     * @param limit
     * @return
     */
    public List<PayMain> selectPayMainListByPage(int start, int limit, String flag, int time) {

        String sql = "select id, pay_id, trade_id, trade_module, pay_way, money, type, status, ext, pay_time, done_time, created_at, updated_at from pay_main where 1 = 1 ";

        Map<String, Object> params = new HashMap<String, Object>(4);
        params.put("start", start);
        params.put("limit", limit);

        if (!StringUtils.isBlank(flag) ) {
            if (AFTER_FLAG.equals(flag)){
                sql += "AND created_at > :time";
            }else {
                sql += "AND created_at <= :time";
            }
            params.put("time", time);
        }

        sql += " order by id ";

        sql += " limit :start, :limit";
        List<PayMain> payMainList = this.payTempJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<PayMain>(PayMain.class));

        String detailSql = "select id, pay_detail_id, pay_id, transaction_id, module, money, module_type, status, ext, done_time, created_at, updated_at from pay_detail where pay_id = :payId ";

        Map<String, Object> detailParams = new HashMap<String, Object>(4);

        for (PayMain payMain : payMainList) {

            detailParams.put("payId", payMain.getPayId());

            List<PaymentDetail> paymentDetailList = this.payTempJdbcTemplate.query(detailSql, detailParams, new BeanPropertyRowMapper<PaymentDetail>(PaymentDetail.class));

            payMain.setPaymentDetailList(paymentDetailList);

        }

        return payMainList;
    }

    /**
     * 组成支付系统支付支付订单流水数据
     *
     * @param payMainList
     * @return
     */
    public List<PayDeal> groupPayDealfromPayMain(List<PayMain> payMainList) {

        List<PayDeal> payDealList = new ArrayList<>();

        PayDeal payDeal;

        for (PayMain paymain : payMainList) {

            List<PaymentDetail> paymentDetailList = paymain.getPaymentDetailList();

            if (paymentDetailList == null || paymentDetailList.isEmpty()) {
//                logger.info("支付订单号 : " + paymain.getPayId() + " , 业务订单号 : " + paymain.getTradeId() + " 没有支付流水信息");

                payDeal = new PayDeal();

                payDeal.setPayChannel("unknown");

                payDeal.setPayId(String.valueOf(paymain.getPayId()));

                payDeal.setPayPaymentNo(String.valueOf(paymain.getPayId()));

                payDeal.setRequestAmount(paymain.getMoney());

                payDeal.setTradeModule(paymain.getTradeModule());

                payDeal.setLshNotifyUrl(notifyUrl);

                payDeal.setSystem(1);//只有1

                payDeal.setPayWay(paymain.getPayWay());

                payDeal.setTradeId(paymain.getTradeId());

                payDeal.setPayType(paymain.getType());

                payDeal.setModuleType(1);

//                if (paymain.getDoneTime() != null && paymain.getDoneTime() > 1000000) {
//
//                    payDeal.setDoneTime(new Date(new Long(paymain.getDoneTime()) * 1000));
//                }

//                if (paymain.getPayTime() != null && paymain.getPayTime() > 1000000) {
//
//                    payDeal.setPayTime(new Date(new Long(paymain.getPayTime()) * 1000));
//                }

//                if (paymain.getCreatedAt() != null) {
//
//                    payDeal.setCreatedAt(new Date(new Long(paymain.getCreatedAt()) * 1000));
//                }

//                if (paymain.getUpdatedAt() != null) {
//
//                    payDeal.setUpdatedAt(new Date(new Long(paymain.getUpdatedAt()) * 1000));
//                }

                transStatus(paymain, payDeal);

                payDealList.add(payDeal);

                continue;
            }

            if (paymentDetailList.size() > 1) {
                logger.info("支付订单号 : " + paymain.getPayId() + " , 业务订单号 : " + paymain.getTradeId() + " 有多条支付流水");
            }

            for (PaymentDetail paymentDetail : paymentDetailList) {

                payDeal = new PayDeal();

                payDeal.setPayId(String.valueOf(paymain.getPayId()));

                payDeal.setPayPaymentNo(String.valueOf(paymentDetail.getPayDetailId()));

                payDeal.setChannelTransaction(paymentDetail.getTransactionId());

                payDeal.setRequestAmount(paymain.getMoney());

                payDeal.setReceiveAmount(paymentDetail.getMoney());

                payDeal.setTradeModule(paymain.getTradeModule());

                payDeal.setExt(paymentDetail.getExt());

                payDeal.setModuleType(paymentDetail.getModuleType());

                payDeal.setLshNotifyUrl(notifyUrl);//TODO 配置

                payDeal.setSystem(1);//只有1

                payDeal.setPayWay(paymain.getPayWay());

                payDeal.setTradeId(paymain.getTradeId());

                payDeal.setPayChannel(paymentDetail.getModule());

                payDeal.setPayType(paymain.getType());

//                if (paymain.getDoneTime() != null && paymain.getDoneTime() > 1000000) {
//
//                    payDeal.setDoneTime(new Date(new Long(paymain.getDoneTime()) * 1000));
//                }
//
//                if (paymain.getPayTime() != null && paymain.getPayTime() > 1000000) {
//
//                    payDeal.setPayTime(new Date(new Long(paymain.getPayTime()) * 1000));
//                }
//
//                if (paymentDetail.getCreatedAt() != null) {
//
//                    payDeal.setCreatedAt(new Date(new Long(paymentDetail.getCreatedAt()) * 1000));
//                }

//                if (paymentDetail.getUpdatedAt() != null) {
//
//                    payDeal.setUpdatedAt(new Date(new Long(paymentDetail.getUpdatedAt()) * 1000));
//                }

                transStatus(paymain, payDeal);

                payDealList.add(payDeal);
            }

        }

        return payDealList;
    }

    private void transStatus(PayMain paymain, PayDeal payDeal) {
        if (paymain.getStatus() != null) {

            if (paymain.getStatus() == 预支付 || paymain.getStatus() == 待支付) {
                payDeal.setPayStatus(PayStatus.CREATE_PAYMENT.getValue());
                payDeal.setOperateStatus(OperateStatus.PAYMENT_NO_CALLBACK.getCode());
            }

            if (paymain.getStatus() == 支付中) {
                payDeal.setPayStatus(PayStatus.PAYING.getValue());
                payDeal.setOperateStatus(OperateStatus.PAYMENT_NO_CALLBACK.getCode());
            }

            if (paymain.getStatus() == 已支付) {
                payDeal.setPayStatus(PayStatus.PAY_SUCCESS.getValue());
                payDeal.setOperateStatus(OperateStatus.PAYMENT_CALLBACK.getCode());
            }

            if (paymain.getStatus() == 支付失败) {
                payDeal.setPayStatus(PayStatus.PAY_FAIL.getValue());
                payDeal.setOperateStatus(OperateStatus.PAYMENT_CALLBACK.getCode());
            }

            if (paymain.getStatus() == 作废 || paymain.getStatus() == 失效) {

                payDeal.setPayStatus(PayStatus.PAY_CLOSE.getValue());
                payDeal.setOperateStatus(OperateStatus.PAYMENT_NO_CALLBACK.getCode());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println(simpleDateFormat.parse("20161101000000").getTime());
    }
//1477929600

}
